package com.yanyeori.framework.elasticjob.job;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.yanyeori.framework.core.util.StringUtil;
import com.yanyeori.framework.elasticjob.configprop.JobConfigProps;
import lombok.extern.slf4j.Slf4j;

/**
 * Job任务管理-创建
 *
 * @author chenkuan 2020/8/19
 */
@Slf4j
public class JobManage {

    private final CoordinatorRegistryCenter registryCenter;
    private final JobConfigProps config;

    public JobManage(CoordinatorRegistryCenter registryCenter, JobConfigProps config) {
        this.registryCenter = registryCenter;
        this.config = config;
    }

    /**
     * 添加SimpleJob任务
     *
     * @param jobService             job服务Bean，必须
     * @param cron                   定时表达式，必须
     * @param shardingTotalCount     任务总分片数，必须
     * @param jobParameter           作业参数
     * @param shardingItemParameters 分片序列号参数(分片序列号和参数用等号分隔，多个键值对用逗号分隔分片序列号从0开始，不可大于或等于作业分片总数如：0=a,1=b,2=c)
     * @param description            作业描述
     */
    public void addSimpleJob(Class<?> jobService, String cron, int shardingTotalCount, String jobParameter, String shardingItemParameters, String description) {
        String jobName = StringUtil.lowerFirst(jobService.getSimpleName());
        // 定义作业核心配置
        JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount).jobParameter(jobParameter).shardingItemParameters(shardingItemParameters).description(description).failover(config.isFailover()).misfire(config.isMisfire()).build();
        // 定义SIMPLE类型配置
        SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(simpleCoreConfig, SimpleJobHandle.class.getCanonicalName());
        // 定义Lite作业根配置
        LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).overwrite(config.isOverwrite()).disabled(config.isDisabled()).build();
        //创建任务
        new JobScheduler(registryCenter, simpleJobRootConfig).init();
        log.info("SimpleJobName [{}] created successful", jobName);
    }
}
